import React, { useState, useContext, useEffect } from "react";
import { useLocation } from "react-router-dom";
import { ethers } from "ethers";
import "../css/forus.css";
import { AppState } from "../App";
import "../css/loader.css";

const SearchResults = () => {
  const App = useContext(AppState);
  const [num, setnum] = useState(0);
  const itemsPerPage = 3; // 每页显示的项目数量
  const [currentPage, setCurrentPage] = useState(1); // 当前页码，默认为第一页
  const [showAdmin, setShowAdmin] = useState(true); // 控制显示管理员或用户的筹款信息
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const keyword = searchParams.get("keyword");
  const [allData, setAllData] = useState([]);
  const [results, setResults] = useState([]);
  const [Useramount, setUseramount] = useState();
  const [loading, setLoading] = useState(true);
  console.log(keyword);
  useEffect(() => {
    const fetchData = async () => {
      try {
        let adminProposals = [];
        let userProposals = [];

        if (App.Foundationcontract) {
          const adminCount = await App.Foundationcontract.requestsNumber();
          for (let i = 0; i < adminCount; i++) {
            const proposal = await App.Foundationcontract.requestions(i);
            if (proposal.completed === false) {
              adminProposals.push({ ...proposal, type: 'admin' });
            }
          }

          const userCount = await App.Foundationcontract.userrequestsNumber();
          for (let i = 0; i < userCount; i++) {
            const proposal = await App.Foundationcontract.userrequestions(i);
            if (proposal.completed === false) {
              userProposals.push({ ...proposal, type: 'user' });
            }
          }
        }

        setAllData([...adminProposals, ...userProposals]);
        
      } catch (error) {
        console.error("Error fetching proposals:", error);
      }
    };
    fetchData();
    setLoading(false);
  }, [App.Foundationcontract]);
  useEffect(() => {
    setLoading(true);
    const handleSearch = () => {
      if (keyword === "") {
        alert("请输入搜索内容");
      } else {
        const a = allData.filter(
          (proposal) =>
            proposal.description && proposal.description.includes(keyword)
        );
        setResults(a)
        
        console.log(results);
      }
    };
    handleSearch();
    setLoading(false);
  }, [keyword, allData, results]);
  const Contribute = async (id, Useramount) => {
    try {
      const tx = await App.Foundationcontract.usersendMoney(id, {
        value: Useramount,
      });
      console.log(tx);
      await tx.wait();
      alert("捐赠成功!");
    } catch (error) {
      console.log(error.message);
      alert("出现问题");
    }
  };
  // 计算要显示的项目的索引范围
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;

  // 根据显示类型过滤结果
  const filteredResults = showAdmin ? results.filter(result => result.type === 'admin') : results.filter(result => result.type === 'user');
  const currentItems = filteredResults.slice(indexOfFirstItem, indexOfLastItem);

  // 计算页码数量
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(filteredResults.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  // 点击页码切换页面
  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  // 切换显示类型
  const toggleDisplay = (type) => {
    setShowAdmin(type === 'admin');
    setCurrentPage(1); // 重置当前页码为第一页
  };
  const Vote = async (nums) => {
    try {
      const tx = await App.Foundationcontract.voteRequest(nums);
      await tx.wait();
      alert("投票成功");
      setnum(num + 1);
    } catch (error) {
      if (error.message === "YOu must be contributor") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };
  const Donate = async (id) => {
    try {
      const tx = await App.Foundationcontract.executeRequest(id);
      await tx.wait();
      alert("捐赠成功！");
      setnum(num + 1);
    } catch (error) {
      if (error.message == "execution reverted: You already Voted") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };
  return (
    <div>
       {loading && <div className="loader"></div>}
      <div className="display-type-container">
        <button onClick={() => toggleDisplay('admin')} className={`display-type-button ${showAdmin ? "active" : ""}`}>
          显示管理员
        </button>
        <button onClick={() => toggleDisplay('user')} className={`display-type-button ${!showAdmin ? "active" : ""}`}>
          显示用户
        </button>
      </div>
      <div class="grid sm:grid-cols-1 lg:grid-cols-3 gap-4">
        {currentItems.length !== 0 ? (
          currentItems.map((e, id) => {
            return (
              <div class="p-4">
                <div class="h-full bg-gray-100 bg-opacity-75 px-8 pt-16 pb-24 rounded-lg overflow-hidden text-center relative dynamic-background">
                  <h2 class="tracking-widest -ml-5 text-15px title-font font-medium text-gray-900 mb-1">
                    筹款方地址
                  </h2>
                  <h2
                    class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                    style={{ fontSize: "11px" }}
                  >
                    {e.recipient}
                  </h2>
                  <h2
                    class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                    style={{ fontSize: "20px" }}
                  >
                    {e.tittle}
                  </h2>
                  <img
                    style={{ width: "300px", height: "300px" }}
                    src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${e.photo}`}
                    alt="Proposal Photo"
                  />
                  <h1 class="title-font sm:text-xl text-lg font-medium text-gray-900 mb-3"></h1>
                  <p class="leading-relaxed mt-5 mb-5">{e.description}</p>
                  {showAdmin ? (
                    <>
                  <div class="text-center mt-2 leading-none flex justify-center absolute bottom-0 left-0 w-full py-4">
                    <span class="text-black  font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      投票数
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {e.votersNumber.toString()}
                    </span>
                    <span class="text-black ml-10 font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      所需金额
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {Number(e.targetMoney.toString())} WEI { }
                    </span>
                  </div>
                  <div className="flex justify-center absolute bottom-10 left-0 w-full py-4">
                    <button
                      onClick={() => Vote(Number(e.uniqueid.toString()))}
                      class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                    >
                      投票
                    </button>
                    <button
                      onClick={() => Donate(Number(e.uniqueid.toString()))}
                      class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                    >
                      捐赠
                    </button>
                  </div>
                  </>
  ) : (
    <>
                  <div class="text-center mt-2 leading-none flex justify-center absolute bottom-0 left-0 w-full py-4">
                    <span class="text-black  font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      已收到
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {e.userraisedAmount.toString()} WEI { }
                    </span>
                    <span class="text-black ml-10 font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      所需金额
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {Number(e.targetMoney.toString())} WEI { }
                    </span>
                  </div>
                  <div className="flex justify-center absolute bottom-10 left-0 w-full py-4">
                    <input
                      type="text"
                      placeholder="Amount in WEI"
                      className="donateInput"
                      onChange={(e) => setUseramount(e.target.value)}
                    />
                    <button
                      onClick={() =>
                        Contribute(
                          e.uniqueid,
                          ethers.utils.parseUnits(Useramount, 0)
                        )
                      }
                      class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                    >
                      捐赠
                    </button>
                  </div> 
                  </>
                )}
                </div>
              </div>
            );
          })
        ) : (
          <div class="flex items-center justify-center nonDIv">
            <div class="title-font sm:text-2xl text-xl font-medium text-gray-900  text-black">
              没有相关内容。
            </div>
          </div>
        )}

      </div>
      {currentItems.length !== 0 && (
        <div className="pagination-container">
          <button
            className={`pagination-button ${currentPage === 1 ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          {pageNumbers.map((number) => (
            <button
              key={number}
              className={`pagination-button ${currentPage === number ? "active" : ""}`}
              onClick={() => handleClick(number)}
            >
              {number}
            </button>
          ))}
          <button
            className={`pagination-button ${currentPage === pageNumbers.length ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage + 1)}
            disabled={currentPage === pageNumbers.length}
          >
            下一页
          </button>
        </div>
      )}
    </div>
  );
};

export default SearchResults;
